package com.datastructure.stack;

public class ArrayStack implements MyStack {
    private int maxSize; //栈容量
    private int[] stack; //存放栈元素
    private int top;  //栈顶元素的下标

    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        stack = new int[this.maxSize];
        top = -1;  //栈空时 top = -1
    }

    public boolean isFull() {
        return top == maxSize - 1;  //数组满了就是栈满了
    }

    public boolean isEmpty() {
        return top == -1;
    }

    //push的时候先确定栈没有满
    //然后top+1，并将新元素存放到该下标处
    public void push (int value) {
        if(isFull()) {
            System.out.println("栈空间已满");
            return;
        }
        top++;
        stack[top] = value;
    }

    //先返回当前top所指的元素
    //然后top-1，指向新的top元素所在位置
    public int pop() {
        if(isEmpty()) {
            System.out.println("栈空");
            throw new RuntimeException("栈空，无法弹出数据");
        }
        return stack[top--];
    }

    public void show() {
        if(isEmpty()) {
            System.out.println("栈空");
            return;
        }
        for(int i=top; i>-1; --i) {
            System.out.printf("stack[%d]=%d\n",i,stack[i]);
        }
    }
}
